//package com.coolweather.android;
//
//import android.content.SharedPreferences;
//import android.os.Bundle;
//import android.preference.PreferenceManager;
//import android.util.Log;
//import android.widget.ArrayAdapter;
//import android.widget.ListView;
//import android.widget.TextView;
//
//
//import androidx.appcompat.app.AppCompatActivity;
//
//import com.coolweather.android.db.City;
//import com.coolweather.android.db.Province;
//import com.coolweather.android.gson.Weather;
//import com.google.gson.Gson;
//
//import org.json.JSONArray;
//import org.json.JSONException;
//import org.json.JSONObject;
//import org.litepal.crud.DataSupport;
//
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.List;
//
//import okhttp3.OkHttpClient;
//import okhttp3.Request;
//import okhttp3.Response;
//
//public class WeatherActivity extends AppCompatActivity {
//    private String mWeatherId;
//    Weather weatherObj;
//    TextView textView;
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_weather);
//        textView = findViewById(R.id.textView2);
//        mWeatherId = getIntent().getStringExtra("weather_id");
//        Log.d("weather_id",mWeatherId);
//        String address="http://guolin.tech/api/weather?cityid="+mWeatherId+"&key=bc0418b57b2d4918819d3974ac1285d9";
//
////        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this);
////        String oldWeatherId = prefs.getString("weatherID",null);
////
////
////        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
////        editor.putString("weatherID",mWeatherId);
////        editor.apply();
////
////         prefs = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this);
////        String weatherString = prefs.getString("weather",null);
////        Log.d("weather1",weatherString);
//        queryDataFromServer(address);
////        if(weatherString.equals("")||!oldWeatherId.equals(weatherString)){
////            queryDataFromServer(address);
////        }else {
////            try {
////                dispWeather(weatherString);
////                textView.setText(weatherObj.basic.cityName);
////            }catch (JSONException e){
////                e.printStackTrace();
////            }
////
////        }
//
//    }
//
//    private void dispWeather(String weatherString)throws JSONException {
//        parseWeatherData(weatherString);
//    }
//
//    private void queryDataFromServer(final String address){
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    OkHttpClient client = new OkHttpClient();
//                    Request request = new Request.Builder().url(address).build();
//                    Response response = null;
//                    response = client.newCall(request).execute();
//                    String responseData = response.body().string();
//                    Log.d("responseData", responseData);
//                    SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
//                    editor.putString("weather",responseData);
//                    editor.apply();
//
//                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this);
//                    String weatherString = prefs.getString("weather",null);
//                    Log.d("weather1",weatherString);
//                    parseWeatherData(responseData);
//                    if(weatherString.equals("")){
//            queryDataFromServer(address);
//        }else {
//            try {
//                dispWeather(weatherString);
//                textView.setText(weatherObj.basic.cityName);
//            }catch (JSONException e){
//                e.printStackTrace();
//            }
//
//        }
//                } catch (IOException | JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }
//    private void parseWeatherData(String responseData) throws JSONException {
//        JSONObject fristLevel= new JSONObject(responseData);
//        JSONArray jsonArray = fristLevel.getJSONArray("HeWeather");
//        String weatherContent = jsonArray.getJSONObject(0).toString();
//        Log.d("parseWeatherData",weatherContent);
//        weatherObj= new Gson().fromJson(weatherContent, Weather.class);
//        Log.d("parseWeatherData",weatherObj.basic.cityName);
//    }
////    private  void show(){
////        ListView list = findViewById(R.id.list_Province1);
////        adapter = new ArrayAdapter<>(WeatherActivity.this, android.R.layout.simple_list_item_2,dataList);
////        list.setAdapter(adapter);
////        provinceList = DataSupport.findAll(Province.class) ;
////        if ( provinceList.size()>0){
////            dataList.clear( ) ;
////            for (Province province : provinceList) {
////                dataList.add(province.getProvinceName());
////            }
////            adapter.notifyDataSetChanged();
////            currentLevel = LEVEL_PROVINCE;
////        }else{
////            String address = "http://guolin.tech/api/weather?cityid=CN101020500&key=bc0418b57b2d4918819d3974ac1285d9";
////            queryDataFromServer(address,"province");
////        }
////    }
//}
package com.coolweather.android;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.coolweather.android.gson.Forecast;
import com.coolweather.android.gson.Weather;
import com.coolweather.android.service.AutoService;
import com.coolweather.android.util.HttpUtil;
import com.google.gson.Gson;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    private String weatherId;
    private Weather weatherobj;
    private TextView cityName;
    private Handler mHandler = new Handler();

    public DrawerLayout drawerLayout;

    public SwipeRefreshLayout swipeRefresh;

    private ScrollView weatherLayout;

    private Button navButton;

    private TextView titleCity;

    private TextView titleUpdateTime;

    private TextView degreeText;

    private TextView weatherInfoText;

    private LinearLayout forecastLayout;

    private TextView aqiText;

    private TextView pm25Text;

    private TextView comfortText;

    private TextView carWashText;

    private TextView sportText;

    private ImageView bingPicImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weatherinfo);
        weatherId = getIntent().getStringExtra("weatherid");
        Log.d("info", weatherId);
        if (weatherId == "") {
            weatherId="CN101060503";
        }
        String address = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9";
        Log.d("info", address);
        queryDataFromServer(address);
        cityName = (TextView) findViewById(R.id.title_city);
        bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
        weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
        titleCity = (TextView) findViewById(R.id.title_city);
        titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
        degreeText = (TextView) findViewById(R.id.degree_text);
        weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        aqiText = (TextView) findViewById(R.id.aqi_text);
        pm25Text = (TextView) findViewById(R.id.pm25_text);
        comfortText = (TextView) findViewById(R.id.comfort_text);
        carWashText = (TextView) findViewById(R.id.car_wash_text);
        sportText = (TextView) findViewById(R.id.sport_text);
        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        //SwipeRefreshLayout刷新组件
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        queryDataFromServer(address);
                        swipeRefresh.setRefreshing(false);
                    }
                },1000);
            }
        });
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navButton = (Button) findViewById(R.id.nav_button);
        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                drawerLayout.openDrawer(GravityCompat.START);
                Intent intent = new Intent(WeatherActivity.this, MainActivity.class);
                startActivity(intent);
                WeatherActivity.this.finish();
            }
        });
        //获取共享数据
//        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Weatherinfo.this);
//        String weatherString = prefs.getString("weather",null);
    }

    /**
     * 显示方法
     */
    private void displayWeather() {
        if (weatherobj !=null&&"ok".equals(weatherobj.status)) {
            Intent intent = new Intent(this, AutoService.class);
            startService(intent);

            Log.d("weainfo", weatherobj.basic.cityName);
            cityName.setText(weatherobj.basic.cityName);
            String cityName = weatherobj.basic.cityName;
            String updateTime = weatherobj.basic.update.updateTime.split(" ")[1];
            String degree = weatherobj.now.temperature + "℃";
            String weatherInfo = weatherobj.now.more.info;
            titleCity.setText(cityName);
            titleUpdateTime.setText(updateTime);
            degreeText.setText(degree);
            weatherInfoText.setText(weatherInfo);
            forecastLayout.removeAllViews();
            for (Forecast forecast : weatherobj.forecastList) {
                View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
                TextView dateText = (TextView) view.findViewById(R.id.date_text);
                TextView infoText = (TextView) view.findViewById(R.id.info_text);
                TextView maxText = (TextView) view.findViewById(R.id.max_text);
                TextView minText = (TextView) view.findViewById(R.id.min_text);
                dateText.setText(forecast.date);
                infoText.setText(forecast.more.info);
                maxText.setText(forecast.temperature.max);
                minText.setText(forecast.temperature.min);
                forecastLayout.addView(view);
            }
            if (weatherobj.aqi != null) {
                aqiText.setText(weatherobj.aqi.city.aqi);
                pm25Text.setText(weatherobj.aqi.city.pm25);
            }
            String comfort = "舒适度：" + weatherobj.suggestion.comfort.info;
            String carWash = "洗车指数：" + weatherobj.suggestion.carWash.info;
            String sport = "出行建议：" + weatherobj.suggestion.sport.info;
            comfortText.setText(comfort);
            carWashText.setText(carWash);
            sportText.setText(sport);
        }else {
            Toast.makeText(WeatherActivity.this,"获取天气数据失败",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 请求服务器数据
     * @param address  请求地址
     */
    public void queryDataFromServer(String address) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(address).build();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Toast.makeText(WeatherActivity.this, "加载失败", Toast.LENGTH_LONG).show();
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String responseData = response.body().string();
                            try {
                                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                                editor.putString("weather",responseData);
                                editor.apply();
                                parseWeatherInfo(responseData);
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        displayWeather();
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 解析json天气数据
     * @param responseData
     */
    public void parseWeatherInfo(String responseData) throws JSONException {
        JSONObject firstlevel = new JSONObject(responseData);//responseData转化为JsonObject
        JSONArray jsonArray = firstlevel.getJSONArray("HeWeather");//解析jsonArry
        String weatherContent  = jsonArray.getJSONObject(0).toString();
        Log.d("info",weatherContent);
        weatherobj = new Gson().fromJson(weatherContent,Weather.class);
        Log.d("info",weatherobj.basic.cityName);
    }

    public static Weather utileatherInfo(String responseData) throws JSONException {
        JSONObject firstlevel = new JSONObject(responseData);//responseData转化为JsonObject
        JSONArray jsonArray = firstlevel.getJSONArray("HeWeather");//解析jsonArry
        String weatherContent  = jsonArray.getJSONObject(0).toString();
        Log.d("info",weatherContent);
        return new Gson().fromJson(weatherContent,Weather.class);
    }
}